package pipe

import (
	"gitee.com/injoyai/goutil/g"
	"gitee.com/injoyai/goutil/net/conn/v2"
	"gitee.com/injoyai/goutil/net/tcp/v2"
	"gitee.com/injoyai/goutil/oss/io"
	"log"
	"time"
)

// WriteWithBase64 数据通讯加密,通道客户端服务端的发送数据函数
func WriteWithBase64(req []byte) []byte {
	req = []byte(g.EncodeBase64(req))
	req = io.WriteWithDefault(req)
	return req
}

// ReadWithBase64 数据通讯解密,通道客户端服务端的读取数据函数
func ReadWithBase64(c *io.Client) (bytes []byte, err error) {
	bytes, err = io.ReadWithDefault(c)
	if err != nil {
		return nil, err
	}
	if len(bytes) > 2+2 {
		bytes = bytes[2 : len(bytes)-2]
	}
	return g.DecodeBase64(string(bytes))
}

// PrintWithPipe 通道服务端打印函数
func PrintWithPipe(tag string, msg *conn.Message) {
	printWithPipe(tag, msg.Key(), msg.String())
}

func printWithPipe(tag, addr, msg string) {
	log.Printf("[pipe][%s][%s] %s\n", tag, addr, msg)
}

// ConnectWithDefault 默认连接函数
func ConnectWithDefault(i io.Writer) func(key, addr string) (cli io.ReadWriteCloser, err error) {
	return func(key, addr string) (io.ReadWriteCloser, error) {
		c, err := tcp.Dial(addr)
		if err == nil {
			log.Printf("[连接][pipe][%s] 连接服务成功...", addr)
			c.SetPrintFunc(func(s string, msg *io.Message) { log.Printf("[%s][pipe][%s] %s\n", s, msg.Key(), msg.String()) })
			c.SetTimeout(time.Second * 10)
			c.SetKey(key)
			c.Debug(false)
			c.SetWriteFunc(nil)
			c.SetReadFunc(io.ReadWithAll)
			c.SetDealFunc(func(msg *conn.Message) { i.Write(NewWriteMsg(key, addr, msg.Bytes()).Bytes()) })
			c.SetCloseFunc(func(msg *conn.Message) {
				i.Write(NewCloseMsg(key, msg.String()).Bytes())
				log.Printf("[错误][%s] %s", msg.Key(), msg.String())
			})
		}
		return c, err
	}
}
